package com.heima.behavior.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取用户ID
        String userId = request.getHeader("userId");
        log.info("获取到用户ID：{}",userId);
        // 如果用户ID不为空，则创建一个WmUser对象并设置用户ID
        if (StringUtils.hasText(userId)) {
            ApUser apUser = new ApUser();
            apUser.setId(Integer.valueOf(userId));
            // 将用户信息存入ThreadLocal
            AppThreadLocalUtil.setUser(apUser);

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtil.remove();
    }
}
